<template>
  <section class="content-section">
    <div class="section-header">
      <h2>请求历史</h2>
      <p>查看和分析所有拦截的网络请求</p>
    </div>

    <div class="request-manager">
      <div class="request-actions">
        <el-button @click="clearRequests">清空历史</el-button>
        <el-button @click="exportRequests">导出数据</el-button>
        <el-button type="primary" @click="refreshRequests">刷新</el-button>
      </div>

      <div class="request-stats">
        <div class="stat-card">
          <h4>总请求数</h4>
          <span>{{ requestStats.total }}</span>
        </div>
        <div class="stat-card">
          <h4>Mock请求数</h4>
          <span>{{ requestStats.mock }}</span>
        </div>
        <div class="stat-card">
          <h4>成功请求</h4>
          <span>{{ requestStats.success }}</span>
        </div>
        <div class="stat-card">
          <h4>失败请求</h4>
          <span>{{ requestStats.error }}</span>
        </div>
      </div>

      <div class="request-list">
        <div class="list-header">
          <span>请求数量</span>
          <span class="count">{{ requestList.length }}</span>
        </div>
        <div class="request-table">
          <table class="custom-table">
            <thead>
              <tr>
                <th style="width: 300px">URL</th>
                <th style="width: 80px">方法</th>
                <th style="width: 80px">状态</th>
                <th style="width: 200px">返回内容</th>
                <th style="width: 150px">时间</th>
                <th style="width: 150px">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(request, index) in requestList" :key="index">
                <td>{{ request.url }}</td>
                <td>{{ request.method }}</td>
                <td>{{ request.status }}</td>
                <td>
                  <el-popover title="responseBody" width="456" trigger="click">
                    <div style="max-width: 500px;overflow:auto;max-height: 560px;">
                      <pre v-html="JSON.stringify(request?.responseBody, null, 2)">
                     </pre>
                    </div>
                    <el-button slot="reference" type="text">查看</el-button>
                  </el-popover>

                </td>
                <td>{{ request.timestamp }}</td>
                <td>
                  <el-button size="mini" @click="viewRequestDetails(request)">查看且mock</el-button>
                </td>
              </tr>
              <tr v-if="requestList.length === 0">
                <td colspan="5" class="empty-row">暂无请求数据</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- 请求详情对话框 -->
      <el-dialog title="请求详情" :visible.sync="dialogVisible" width="60%" :before-close="handleCloseDialog">
        <el-form :model="currentRequest" label-width="80px">
          <el-form-item label="URL:">
            <el-input v-model="currentRequest.url" readonly></el-input>
          </el-form-item>
          <el-form-item label="方法:">
            <el-input v-model="currentRequest.method" readonly></el-input>
          </el-form-item>
          <el-form-item label="状态:">
            <el-input v-model="currentRequest.status" readonly></el-input>
          </el-form-item>
          <el-form-item label="时间:">
            <el-input v-model="currentRequest.timestamp" readonly></el-input>
          </el-form-item>
          <el-form-item label="响应:">
            <el-input v-model="currentRequest.responseBody" type="textarea" :rows="8" placeholder="请输入响应内容"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="handleSaveResponse">保存为mock</el-button>
        </div>
      </el-dialog>
    </div>
  </section>
</template>
<script>
import { getStorage, setStorage } from '../../../utils/chrome'

export default {
  name: 'RequestPage',
  data() {
    return {
      requestList: [],
      requestStats: {
        total: 0,
        success: 0,
        error: 0
      },
      // 对话框控制
      dialogVisible: false,
      currentRequest: {
        url: '',
        method: '',
        status: '',
        timestamp: ''
      },
      responseContent: ''
    }
  },

  mounted() {
    this.loadRequestList()
  },

  methods: {
    // 加载请求列表
    async loadRequestList() {
      try {
        const saved = await getStorage('requestList')
        if (saved && saved.requestList) {
          this.requestList = saved.requestList
          this.updateRequestStats()
        }
      } catch (error) {
        console.error('加载请求列表失败:', error)
      }
    },

    // 保存请求列表
    async saveRequestList() {
      try {
        await setStorage({'requestList':this.requestList})
      } catch (error) {
        console.error('保存请求列表失败:', error)
      }
    },

    // 清空请求历史
    clearRequests() {
      this.$confirm('确定要清空所有请求历史吗？', '确认', {
        type: 'warning'
      }).then(async () => {
        this.requestList = []
        this.updateRequestStats()
        await this.saveRequestList()
        this.$message.success('请求历史清空成功')
      })
    },

    // 导出请求数据
    exportRequests() {
      if (this.requestList.length === 0) {
        this.$message.warning('没有请求数据可导出')
        return
      }

      const data = {
        requestList: this.requestList,
        exportTime: new Date().toISOString(),
        total: this.requestList.length
      }

      const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `interceptor-requests-${new Date().toISOString().split('T')[0]}.json`
      a.click()
      URL.revokeObjectURL(url)

      this.$message.success('请求数据导出成功')
    },

    // 刷新请求列表
    refreshRequests() {
      this.loadRequestList()
      this.$message.success('请求历史刷新成功')
    },

    // 查看请求详情
    viewRequestDetails(request) {
      // 设置当前请求数据
      this.currentRequest = {
        url: request.url,
        method: request.method,
        status: request.status,
        timestamp: request.timestamp,
        responseBody: request.responseBody
      }
      // 设置响应内容（如果存在）
      this.responseContent = request.response || ''
      // 打开对话框
      this.dialogVisible = true
    },

    // 从请求创建Mock规则
    createMockFromRequest(request) {
      // 触发父组件事件，切换到Mock页面并创建规则
      this.$emit('create-mock-from-request', request)
      this.$message.success('已切换到Mock规则页面，请完善Mock配置')
    },

    // 关闭对话框
    handleCloseDialog() {
      this.dialogVisible = false
      this.currentRequest = {
        url: '',
        method: '',
        status: '',
        timestamp: ''
      }
      this.responseContent = ''
    },

    // 保存响应内容到Mock列表
    async handleSaveResponse() {
      try {
        // 创建Mock规则对象
        const mockRule = {
          id: Date.now().toString(),
          url: this.currentRequest.url,
          method: this.currentRequest.method,
          enabled: true,
          response: this.currentRequest?.responseBody,
          statusCode: this.currentRequest.status || 200,
          headers: {
            'Content-Type': 'application/json'
          },
          delay: 0,
          createTime: new Date().toISOString(),
          description: `从请求历史创建的Mock规则 - ${this.currentRequest.url}`
        }

        // 获取现有的mockList
        const saved = await getStorage('mockList')
        const mockList = (saved && saved.mockList) ? saved.mockList : []

        // 检查是否已存在相同URL的Mock规则
        const existingIndex = mockList.findIndex(mock => mock.url === this.currentRequest.url)

        if (existingIndex !== -1) {
          // 如果存在，更新现有规则
          mockList[existingIndex] = {
            ...mockList[existingIndex],
            method: this.currentRequest.method,
            response: this.currentRequest?.responseBody,
            statusCode: this.currentRequest.status || 200,
            updateTime: new Date().toISOString(),
            description: `从请求历史更新的Mock规则 - ${this.currentRequest.url}`
          }
        } else {
          // 如果不存在，添加新的mock规则
          mockList.push(mockRule)
        }

        console.log("🚀 ~ handleSaveResponse ~ mockList:", mockList)


        // 保存到Chrome存储
        await setStorage({mockList: mockList})

        this.$message.success('Mock规则已保存')
        this.handleCloseDialog()
      } catch (error) {
        console.error('保存Mock规则失败:', error)
        this.$message.error('保存Mock规则失败')
      }
    },

    // 更新请求统计
    updateRequestStats() {
      this.requestStats.total = this.requestList.length
      this.requestStats.mock = this.requestList.filter(r => r.isMock).length
      this.requestStats.success = this.requestList.filter(r => r.status >= 200 && r.status < 300).length
      this.requestStats.error = this.requestList.filter(r => r.status >= 400).length
    }
  }
}
</script>

<style scoped>
/* 请求管理器样式 */
.request-manager {
  padding: 30px;
}

.request-actions {
  display: flex;
  gap: 10px;
  margin-bottom: 30px;
}

.request-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  text-align: center;
  transition: all 0.2s ease;
}

.stat-card:hover {
  border-color: #667eea;
  box-shadow: 0 2px 12px rgba(102, 126, 234, 0.1);
}

.stat-card h4 {
  font-size: 14px;
  color: #6c757d;
  margin-bottom: 8px;
  font-weight: 500;
}

.stat-card span {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
}

.request-list {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-weight: 500;
  color: #2c3e50;
}

.count {
  background: #667eea;
  color: white;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 14px;
  font-weight: 500;
}

.request-table {
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.custom-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.custom-table th,
.custom-table td {
  padding: 12px 8px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

.custom-table th {
  background-color: #f5f7fa;
  font-weight: 500;
  color: #909399;
}

.custom-table tbody tr:hover {
  background-color: #f5f7fa;
}

.custom-table .empty-row {
  text-align: center;
  color: #909399;
  font-style: italic;
}

/* 对话框样式 */
.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 10px;
}
</style>